//
//  SpeakViewController.m
//  FanXi
//
//  Created by MujiEDU on 15/10/30.
//  Copyright © 2015年 cx. All rights reserved.
//

#import "MujiDubViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "MujiDubHeader.h"
#import "MujiDubVCTableViewCell.h"
#import "ContentManager.h"
#import "MujiDubDialogLinesModel.h"
#import "MujiDubTextHeightTool.h"
#import "MujiDubWordModel.h"
#import "MujiDubDatabaseManager.h"
#import "MujiDubRecordModel.h"
#import "MujiDubDictionaryView.h"
#import "MujiDubPreviewTableViewCell.h"
#import "MujiDubProgressView.h"
#import "MujiDubFilePathUtility.h"
#import "MujiHUDManager.h"
#import "MujiDubTools.h"
#import "MujiAudioComposition.h"
#import "MujiDubRecordModel.h"

typedef void(^getModelData)();

#define kTableViewCellReusedID @"kTableViewCellReusedID"
#define kTableViewPreviewCellReusedID @"kTableViewPreviewCellReusedID"

#define SCREEN_WIDTH    [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT    [[UIScreen mainScreen] bounds].size.height

static void *TableViewScrollContext = &TableViewScrollContext;


@interface MujiDubViewController () < MujiDubRecorderDelegate, UITableViewDataSource, UITableViewDelegate, MujiDubPreviewTableViewCellDelegate, UIScrollViewDelegate, MujiDubVCTableViewCellDelegate>

//@property (nonatomic, strong) IFlySpeechEvaluator *iFlySpeechEvaluator;
@property (nonatomic, assign) BOOL isSessionEnd;
@property (nonatomic, assign) BOOL isRecording;
@property (nonatomic, assign) int mIndex;
@property (nonatomic, assign) int mOffent;
@property (nonatomic, assign) int mVideoHeight;
@property (nonatomic, strong) NSString* resultText;
@property (nonatomic, strong) NSMutableArray* metaArray;
@property (nonatomic, strong) NSMutableDictionary* resultArray;
@property (nonatomic,strong)  NSTimer *avTimer;
@property (nonatomic,strong)  UIWebView *showTextview;
@property (nonatomic, strong) UIButton *slowPlayBtn;
@property (readwrite, nonatomic, assign) Float64 previousVideoTimeSeconds;
@property (nonatomic, assign) BOOL isReady;
@property (nonatomic, strong) NSMutableDictionary *scoreArray;
@property (nonatomic, strong) NSMutableArray   *dialogLineIdArray;
@property (nonatomic, strong) NSMutableDictionary   *resultXML;
@property (nonatomic, strong) NSMutableArray   *lineIndexArray;
@property (nonatomic, strong) NSDate *recordDate;

@property (nonatomic,strong) UIImageView *playImageView;
@property (nonatomic,strong) NSMutableArray *dialogArray;
@property (nonatomic,strong) NSMutableArray *wordArray;
@property (nonatomic,strong) MujiDubDictionaryView *letterView;
@property (nonatomic,strong) UIButton *selectBtn;

// 已录音记录
@property (nonatomic,strong) NSMutableArray *myResultArray;
@property (nonatomic,strong) MBProgressHUD *hud;

@property (nonatomic,assign) int                   curFontSize;
@property (nonatomic,assign) int                   curTransFontSize;
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,assign) int                   curSelect;
@property (nonatomic,strong) NSMutableArray *itemHeightArray;
@property (nonatomic, strong, readwrite) NSTimer *slowSpeakAudioTimer;
@property (nonatomic, assign, readwrite) double slowSpeakStart;
@property (nonatomic, assign, readwrite) double slowSpeakEnd;

@property (nonatomic,strong) MujiDubVCTableViewCell *curCell;

@property (nonatomic, strong) UIImageView   *guide;

// 是否添加引导标示
@property (nonatomic, assign) BOOL   isGuideAdded;
@property (nonatomic, strong) UIProgressView* progressView;

// 视频准备好 播放
@property (nonatomic, assign) BOOL bHasReadyForPlay;

// 全部句子录音完成标示
@property (nonatomic, assign) BOOL   isAllSpeak;

// 视频播放标示
@property (nonatomic, assign) BOOL   playing;
// 视频暂停标示
@property (nonatomic, assign) BOOL   stop;

@property (nonatomic, strong) AVAudioPlayer *avAudioPlayer;
@property (nonatomic, copy) NSString   *lineScore;
// 录音播放中
@property (nonatomic, assign) BOOL   isRecordPlaying;
// 预览状态
@property (nonatomic, assign) BOOL   preViewStatus;
// 开始播放录音
@property (nonatomic, assign) BOOL   dubRecordPlayBegin;

//@property (nonatomic, assign) BOOL   videoTimeTickStop;
// 暂停视频播放
@property (nonatomic, assign) BOOL   isVideoTapStop;
// 正在seek视频标示
@property (nonatomic, assign) BOOL   isVideoSeeking;
// 播放器音量
@property (nonatomic, assign) float  playerVolume;
// 播放录音结束
@property (nonatomic, assign) BOOL   playRecordFinish;
//定时器
@property (nonatomic, strong)  dispatch_source_t timer;
//  录音开始时间
@property (nonatomic, strong)  NSDate  *timerBegintime;
// 预览配音  录音播放器暂停标示
@property (nonatomic, assign) BOOL   avAudioPlayerPause;
// 预览配音  录音播放器播放标示
@property (nonatomic, assign) BOOL   avAudioPlayerPlaying;
// 预览配音  录音播放器开始标示
@property (nonatomic, assign) BOOL   previewRecordPlayBegin;

@property (nonatomic, assign) BOOL   mergeDataFinish;


//  暂停播放录音开始时间
@property (nonatomic, strong)  NSDate  *playingRecordPauseBegintime;

//  暂停播放录音结束时间
@property (nonatomic, strong)  NSDate  *playingRecordPauseEndtime;

@property (nonatomic, assign) BOOL   playVideoAndRecord;

@end


@implementation MujiDubViewController

@synthesize timeObserver                     = _timeObserver;
//@synthesize dialogLineAnalysisResult                    = _dialogLineAnalysisResult;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _isGuideAdded = NO;
    _bHasReadyForPlay = NO;
    _isAllSpeak = NO;
    _preViewStatus = NO;
    _dubRecordPlayBegin = NO;
    //self.videoTimeTickStop = NO;
    self.isVideoTapStop = NO;
    
    self.isVideoSeeking = NO;
    self.playRecordFinish = NO;
    self.avAudioPlayerPause = NO;
    self.avAudioPlayerPlaying = NO;

    self.isRecordPlaying = NO;
    self.previewRecordPlayBegin = NO;
    //[self.view addSubview:self.guide];
    _playing = YES;
    _stop = NO;
    
    _curFontSize = 18;
    _curTransFontSize = 12;
    if(kIS_IPHONE_6)
    {
        _curFontSize = 18;
        _curTransFontSize = 14;
    }
    
    self.itemHeightArray = [NSMutableArray array];
    self.metaArray = [[NSMutableArray alloc] init];
   // self.imageviwArray = [[NSMutableArray alloc] init];
    self.myResultArray = [[NSMutableArray alloc] init];
    self.resultArray = [NSMutableDictionary dictionaryWithCapacity:5];
    self.scoreArray = [[NSMutableDictionary alloc] init];
    self.dialogLineIdArray = [[NSMutableArray alloc] init];
    self.resultXML = [[NSMutableDictionary alloc] init];
    self.lineIndexArray = [[NSMutableArray alloc] init];
    self.wordArray = [[NSMutableArray alloc] init];

    self.isRecording = NO;
    self.isReady = NO;
    self.mVideoHeight = 220;
    self.mIndex = 0;
//    [self createResultDB];
    
    
    //self.dialogId = @"123456";
    //self.dia = @"654321";

    [self getResultFromDB];
    
   // self.videoUrl =  [NSString stringWithFormat:@"http://data.gearedu.com/dialogs/%@/%@.mp4", self.dialogId,self.dialogId];
    /*
     http://rongyao1.oss-cn-hangzhou.aliyuncs.com/demo/demo.json
     
     http://rongyao1.oss-cn-hangzhou.aliyuncs.com/demo/demo.avi
     
     http://rongyao1.oss-cn-hangzhou.aliyuncs.com/demo/demo_voice.mp4

     http://rongyao1.oss-cn-hangzhou.aliyuncs.com/demo/demo.mp4
     
     */
    
    if (self.videoUrl.length == 0) {
        self.videoUrl = [NSString stringWithFormat:@"http://rongyao1.oss-cn-hangzhou.aliyuncs.com/demo/demo_voice.mp4"];
    }
    
    //  是否显示中文字幕
    self.isShowChinese = YES;

    
    [self initUI];
    NSString *chineseScriptStatus = [[NSUserDefaults standardUserDefaults] objectForKey:videoChineseScript];
    if(chineseScriptStatus == nil){
        self.isShowChinese = YES;
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:videoChineseScript];
    }
    else{
        if([chineseScriptStatus isEqualToString:@"0"]){
            self.isShowChinese = NO;
        }
        else{
            self.isShowChinese = YES;
        }
    }
    
    if(self.isShowChinese)
    {
        [self.scriptButton setTitleColor:ColorWithRGBA(232, 50, 40, 1) forState:UIControlStateNormal];
        [self.scriptButton.layer setBorderColor:ColorWithRGBA(232, 50, 40, 1).CGColor];
    }
    else
    {
        [self.scriptButton setTitleColor:ColorWithRGBA(0, 0, 0, 0.65) forState:UIControlStateNormal];
        [self.scriptButton.layer setBorderColor:ColorWithRGBA(0, 0, 0, 0.65).CGColor];
    }
    
    [self getAllSpeakData];
    
    [[MujiDubTools share] observeNetReachability];

    //  视频加载完成 可以播放的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerPlay:)
                                                 name:@"kPlayerPlay" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [self.videoPlayerView pause];
    [super viewWillDisappear:animated];
}

// 获取metadata   视频段落句子的一些数据
-(void)getAllSpeakData
{
#if 1
    
    ContentManager * __weak weakContentManager =  [ContentManager sharedManager];
    [weakContentManager getDialogCompleteMetaDataWithID:self.dialogId
                                                success:^(id dialogContent)
     {
         //return;
         if (dialogContent == nil) {
             return;
         }
         //self.slowSpeakAudioURL = [NSURL URLWithString:dialogContent[@"slowSpeakAudioURL"]];
         
         //self.duration = dialogContent[@"duration"];
#if 1
         if (dialogContent) {
             for (id obj in dialogContent) {
                 
                 MujiDubDialogLinesModel *dialogLinesModel = [[MujiDubDialogLinesModel alloc] init];
                 [dialogLinesModel setValuesForKeysWithDictionary:obj];
                 dialogLinesModel.dialogId = self.dialogId;
                 
                 dialogLinesModel.cueEnd = dialogLinesModel.curEnd;
                 dialogLinesModel.cueStart = dialogLinesModel.curStart;
                 
                 dialogLinesModel.dialogLineID = [NSString stringWithFormat:@"%d", (int)[dialogContent indexOfObject:obj] + 1];
                 
                // NSLog(@"%@", dialogLinesModel);

                 [self.metaArray addObject:dialogLinesModel];
                 
                 if (self.metaArray.count == 0) {
                     return;
                 }

                  NSMutableArray *words = [[NSMutableArray alloc] init];
                 
                  if (obj[@"transcript"]) {
                      NSArray *array = [obj[@"transcript"] componentsSeparatedByString:@" "];
                      
                      for (id obj1 in array) {
                          MujiDubWordModel *wordModel = [[MujiDubWordModel alloc] init];
                          //[wordModel setValuesForKeysWithDictionary:obj1];
                          
                          [wordModel setValue:obj1 forKey:@"orthography"];
                          
                          if (![wordModel.orthography isEqualToString:@""]) {
                              [words addObject:wordModel];
                          }
                      }
                  }
                 [self.wordArray addObject:words];
             }
         }
#endif
#if 0
         if (dialogContent) {
             
             for (int i = 0; i < 10; i++) {
                 
                 id obj = [dialogContent objectAtIndex:i];
                 
                 MujiDubDialogLinesModel *dialogLinesModel = [[MujiDubDialogLinesModel alloc] init];
                 [dialogLinesModel setValuesForKeysWithDictionary:obj];
                 dialogLinesModel.dialogId = self.dialogId;
                 
                 dialogLinesModel.cueEnd = dialogLinesModel.curEnd;
                 dialogLinesModel.cueStart = dialogLinesModel.curStart;
                 
                 dialogLinesModel.dialogLineID = [NSString stringWithFormat:@"%d", (int)[dialogContent indexOfObject:obj] + 1];
                 
                 [self.metaArray addObject:dialogLinesModel];
                 
                 if (self.metaArray.count == 0) {
                     return;
                 }
                 
                 NSMutableArray *words = [[NSMutableArray alloc] init];
                 
                 //NSArray *words = [[NSArray alloc] init];
                 
                 if (obj[@"transcript"]) {
                     NSArray *array = [obj[@"transcript"] componentsSeparatedByString:@" "];
                     
                     for (id obj1 in array) {
                         MujiDubWordModel *wordModel = [[MujiDubWordModel alloc] init];
                         //[wordModel setValuesForKeysWithDictionary:obj1];
                         
                         [wordModel setValue:obj1 forKey:@"orthography"];
                         
                         [words addObject:wordModel];
                     }
                 }
                 [self.wordArray addObject:words];
             }
         }
#endif
         
         [self initPlayer];
         [self calAllItemHeight];
         
         if (self.myResultArray.count != 0) {
             if (self.myResultArray.count == self.metaArray.count) {
                 self.isAllSpeak = YES;
                 [self.tableView reloadData];

             }else {
                 NSMutableArray *dialogIdArr = [NSMutableArray arrayWithCapacity:10];
                 NSMutableArray *myDialogIdArr = [NSMutableArray arrayWithCapacity:10];
                 NSMutableArray *indexArr = [NSMutableArray arrayWithCapacity:10];
                 NSMutableArray *myindexArr = [NSMutableArray arrayWithCapacity:10];

                 
                 for (MujiDubDialogLinesModel *line in self.metaArray) {
                     [dialogIdArr addObject:line.dialogLineID];
                 }
                 
                 for (int i=0; i<self.metaArray.count; i++) {
                     MujiDubDialogLinesModel *line = self.metaArray[i];
                     [indexArr addObject:[NSString stringWithFormat:@"%d", i]];
                 }
                 
                 for (MujiDubRecordModel *result in self.myResultArray) {
                     
                     [myDialogIdArr addObject:[NSNumber numberWithInt:[result.dialoglineid intValue]]];
                     [myindexArr addObject:result.mindex];
                     
                     //NSLog(@"%@", result.mindex);
                 }
                 
                 //[dialogIdArr removeObjectsInArray:myDialogIdArr];
                 
                 [indexArr removeObjectsInArray:myindexArr];
                 
                 NSComparator finderSort = ^(id string1,id string2){
                     
                     if ([string1 integerValue] > [string2 integerValue]) {
                         return (NSComparisonResult)NSOrderedDescending;
                     }else if ([string1 integerValue] < [string2 integerValue]){
                         return (NSComparisonResult)NSOrderedAscending;
                     }
                     else
                         return (NSComparisonResult)NSOrderedSame;
                 };
                 
                 //数组排序：
                 NSArray *resultArray = [indexArr sortedArrayUsingComparator:finderSort];
                 
                 //NSLog(@"%@", resultArray);
                 
                 self.mIndex = [[resultArray firstObject] intValue];
                 
                 [self.tableView reloadData];
                 
                 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.mIndex inSection:0];
                 
                 
                 self.curCell = (MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                 
                 [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
             }
         }else {
             [self.tableView reloadData];
         }
     }
        failure:^(NSError *error)
     {
         //NSLog(@"----");
     }
     ];
#endif
}



- (void)videoPlayerView:(MujiVideoPlayerView *)videoPlayerView
isReadyForVisualDisplay:(BOOL)readyForVisualDisplay
{
    
    if (readyForVisualDisplay && _bHasReadyForPlay == NO)
    {
        NSLog(@"---play----");
        
        _bHasReadyForPlay = YES;
        [self hideAllHUDsAnimated:YES];
        [self startPlayingVideoIfEverythingIsReady];
    }
}

-(void)getFirstNotComplete
{
//    for(int i = 0; i < _metaArray.count; i ++)
//    {
//        MujiDubDialogLinesModel * model = [_metaArray objectAtIndex:i];
//        BOOL bFind = NO;
//        for(int j = 0; j < self.myResultArray.count; j ++)
//        {
//            SpeakResultModel *resultmodel = [self.myResultArray objectAtIndex:j];
//            if([model.dialogLineID isEqualToString:resultmodel.dialoglineid])
//            {
//                bFind = YES;
//                break;
//            }
//        }
//        
//        if(!bFind )
//        {
//            self.mIndex = i;
//            break;
//        }
//    }
}

- (void)startPlayingVideoIfEverythingIsReady
{
    [self getFirstNotComplete];
    
    [self myPlayAction];
}

-(void)myPlayAction
{
    self.duration = [NSString stringWithFormat:@"%.0f", self.mediaAssetLoader.duration];
    if (!self.loadingView.hidden) {
        self.loadingBackView.hidden = YES;
        self.loadingView.hidden = YES;
    }
    self.tableView.userInteractionEnabled = YES;

    self.playButton.hidden = YES;
    [self.videoPlayerView pause];
    [self tearDownTimeObserverOnPlayer:self.videoPlayerView.player];
    
    
    [self playVideo];
}
//  app进入前台
- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    // printf("按理说是重新进来后响应\n");
    
    
    if (self.preViewStatus) {//  预览模式下进入的后台
        
//        self.avAudioPlayerPause = NO;
//        
//        [self.videoPlayerView play];
//        [self.avAudioPlayer play];
        
        
        
    }else {
        [self playVideo];

    }
    
}

//  app进入后台
- (void)applicationWillResignActive:(NSNotification *)notification
{
   // [super applicationWillResignActive:notification];
    [self hideRecordAllHUDsAnimated:NO];
    
    printf("------applicationWillResignActive------");
    
    if ([self.avAudioPlayer isPlaying]) {
        [self.avAudioPlayer pause];
    }
    if ([self.slowSpeakAudioPlayer isPlaying]) {
        [self.slowSpeakAudioPlayer pause];
    }
    
    [self.videoPlayerView pause];
    
    self.avAudioPlayerPause = YES;

    self.isRecording = NO;
    self.playRecordFinish = NO;
    
    self.isRecordPlaying = NO;
    self.isVideoSeeking = NO;
    self.playButton.hidden = YES;

    if (self.preViewStatus) {//  预览模式下进入后台
        
        self.playButton.hidden = NO;
        //self.timeView.hidden = NO;
    
    }
    MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];

    //[cell closeAllPlay];
    
    [cell stopRecording];
    
}

-(void)initUI
{
    self.curSelect = 0;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.videoPlayerView.frame), kScreenWidth, kScreenHeight - 20 - self.videoPlayerView.frame.size.height) style:UITableViewStylePlain];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self.tableView registerClass:[MujiDubVCTableViewCell class] forCellReuseIdentifier:kTableViewCellReusedID];
    [self.tableView registerNib:[UINib nibWithNibName:@"MujiDubPreviewTableViewCell" bundle:nil] forCellReuseIdentifier:kTableViewPreviewCellReusedID];
    

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.decelerationRate = 0.01;
    self.tableView.userInteractionEnabled = NO;
    self.tableView.backgroundColor = ColorWithRGBA(242, 242, 242, 1.0);
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //隐藏TableView多余的分割线
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setTableFooterView:v];
    
    [self.view addSubview:self.tableView];
    
    self.view.backgroundColor = [UIColor colorWithRed:0.957 green:0.961 blue:0.925 alpha:1.000];
    
    self.progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    

    self.progressView.frame =  CGRectMake(0, kScreenHeight - 4, kScreenWidth, 4);
    self.progressView.trackTintColor =  ColorWithRGBA(222, 222, 222, 1.0);
    self.progressView.progressTintColor = ColorWithRGBA(232, 50, 40, 1.0);
    [self.progressView setProgress:0.5];
   // [self.view addSubview:self.progressView];
    
    [self.switchButton setTitle:@"看视频" forState:UIControlStateNormal];
    
    UIButton *testBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, 50, 39, 39)];
    //self.backBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
//    [testBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_back_white"] forState:UIControlStateNormal];
//    [testBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_back_white"] forState:UIControlStateHighlighted];
    [testBtn addTarget:self action:@selector(testBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    testBtn.backgroundColor = [UIColor redColor];
    
   // [self.view addSubview:testBtn];
    
}

- (void)addGuideView
{
//    int status = [[[NSUserDefaults standardUserDefaults] objectForKey:isFirstSpeak] intValue];
//    if (status == 0) {
//        //UIImage *image = [UIImage imageNamed:@"taskguide"];
//        
//        _isGuideAdded = YES;
//        // _guide = [GuideView viewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) image:image xPosition:0 yPositon:kScreenHeight-100-20-100-20-10];
//        //        _guide = [GuideView viewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) image:image xPosition:0 yPositon:439];
//        //
//        //        _guide.tag = 11111;
//        //        _guide.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];
//        //        _guide.userInteractionEnabled = YES;
//        
//        _guide = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//        
//        if (kScreenWidth < 375) {
//            _guide.image = [UIImage imageNamed:@"speak_guide@3x"];
//            
//        }else {
//            _guide.image = [UIImage imageNamed:@"speak_guide@3x"];
//            
//        }
//        _guide.contentMode = UIViewContentModeScaleAspectFill;
//        _guide.userInteractionEnabled = YES;
//        
//        [[UIApplication sharedApplication].keyWindow addSubview:_guide];
//        
//        UITapGestureRecognizer *hideTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideTapHandle:)];
//        [_guide addGestureRecognizer:hideTap];
//    }
}

- (void)hideTapHandle:(UITapGestureRecognizer *)tap
{
//    [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:isFirstSpeak];
//    [_guide removeFromSuperview];
}


#pragma mark -  UITableViewDataSource
// 获取cell高度
-(void)calAllItemHeight
{
    [self.itemHeightArray removeAllObjects];
    for(int i = 0; i < self.metaArray.count; i ++)
    {
        [self.itemHeightArray addObject: [NSNumber numberWithFloat: [self calItemHeight:i]]];
    }
    
    if(self.isNoChinese){
        [self.scriptButton setTitleColor:ColorWithRGBA(0, 0, 0, 0.65) forState:UIControlStateNormal];
        [self.scriptButton.layer setBorderColor:ColorWithRGBA(0, 0, 0, 0.65).CGColor];
    }
    
}
//  计算cell高度
-(CGFloat)calItemHeight:(int) index
{
    MujiDubDialogLinesModel *model = [self.metaArray objectAtIndex:index];
    
    
    //model.translation = @"呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵";

    NSMutableArray *letters = [[NSMutableArray alloc] init];
    NSMutableString *transcript = [NSMutableString stringWithString:model.transcript];
    NSMutableString *lowTranscipt = [NSMutableString stringWithString:[transcript lowercaseString]];
    NSString *curTail = @"";
    
    for (int j = 0; j < [self.wordArray[index] count]; j++)
    {
        NSRange range = [lowTranscipt rangeOfString:[NSString stringWithFormat:@"%@",[((MujiDubWordModel *)self.wordArray[index][j]).orthography lowercaseString]]];
        
        if(j == [self.wordArray[index] count] - 1)
        {
            if(range.location + range.length < lowTranscipt.length)
            {
                curTail = [transcript substringFromIndex:range.location + range.length];
            }
        }
        
        if (range.location != NSNotFound) {
            
            [letters addObject:[transcript substringToIndex:range.location+[((MujiDubWordModel *)self.wordArray[index][j]).orthography lowercaseString].length]];
            transcript = [NSMutableString stringWithString:[transcript substringFromIndex:range.location+[((MujiDubWordModel *)self.wordArray[index][j]).orthography lowercaseString].length]];
            lowTranscipt = [NSMutableString stringWithString:[lowTranscipt substringFromIndex:range.location+[((MujiDubWordModel *)self.wordArray[index][j]).orthography lowercaseString].length]];
        }
    }
    
    CGFloat totalWidth = 20;
    int lines = 0;
    CGFloat lastY = 0;
    
    CGFloat height_single = [MujiDubTextHeightTool getHeightWithString:@"faffafaf" width:self.view.frame.size.width-24 font:_curFontSize].height;
    
    for (int j = 0; j < letters.count; j++) {

        CGFloat width = [MujiDubTextHeightTool getHeightWithString:letters[j] width:self.view.frame.size.width-24 font:_curFontSize].width;
        CGFloat height = [MujiDubTextHeightTool getHeightWithString:letters[j] width:self.view.frame.size.width-24 font:_curFontSize].height;
        
        totalWidth += width;
        if (totalWidth > self.view.frame.size.width - 24 - 20*2) {
            lines++;
            totalWidth = 20;
            totalWidth += width;
        }
        if(j == letters.count - 1)
        {
            //lastY = CGRectGetMaxY(btn.frame);
            if(![curTail isEqualToString:@""])
            {
                CGFloat tail_width = [MujiDubTextHeightTool getHeightWithString:curTail width:self.view.frame.size.width-24 font:_curFontSize].width;
                
                CGFloat tail_height = [MujiDubTextHeightTool getHeightWithString:curTail width:self.view.frame.size.width-24 font:_curFontSize].height;
                
                UILabel *tailLbl = [[UILabel alloc] initWithFrame:CGRectMake(totalWidth, height_single * lines + 5 * (lines + 1), tail_width, tail_height)];
                tailLbl.text =  curTail;
                tailLbl.font = [UIFont systemFontOfSize:_curFontSize];
                totalWidth += tail_width;
                
                if (totalWidth > self.view.frame.size.width - 24 - 20*2) {
                    lines++;
                    totalWidth = 20;
                    tailLbl.frame = CGRectMake(totalWidth, height_single * lines + 5 * (lines + 1), tail_width, tail_height);
                    totalWidth += width;
                    
                }
               
                if(height > height_single)
                {
                    lastY = height + height_single * (lines - 1) + 5 * (lines + 1) + tail_height;
                }
                else
                {
                    lastY = height_single * lines + 5 * (lines + 1) + tail_height;
                }
            }
            else
            {
                lastY = height_single * lines + 5 * (lines + 1) + height;
            }
        }
    }
    //NSLog(@"%f", lastY);
    
    CGFloat totalHeight = 0;
    if(self.isShowChinese)
    {
        if( model!=nil && model.translation.length > 0)
        {
            CGFloat translationHeight = [MujiDubTextHeightTool getHeightWithString:model.translation width:self.view.frame.size.width - 12 - 12 - 20 - 20 font:_curTransFontSize].height + 5;
        
            totalHeight = lastY + translationHeight + 16;
            
        }
        else
        {
            totalHeight += lastY ;
        }
    }
    else
    {
        totalHeight += lastY;
    }
    
    if( model!=nil && model.translation.length > 0)
    {
        self.isNoChinese = NO;
    }
    
    
    CGFloat height = 10 + 20 + totalHeight + 30 + 48 + 10;
    
    //NSLog(@"---------%f    %f   %d", height, (kScreenHeight - SCREEN_WIDTH/16*9 - 20)/2.5, index);
    
    if (height <= (kScreenHeight - SCREEN_WIDTH/16*9 - 20)/2.5) {
        height = (kScreenHeight - SCREEN_WIDTH/16*9 - 20)/2.5;
        //NSLog(@"%f", height);
    }
    
    return height;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.metaArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.row < self.metaArray.count) {
        MujiDubVCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellReusedID forIndexPath:indexPath];
        cell.userInteractionEnabled = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.parentVC = self;
        cell.index = (int)indexPath.row;
        cell.totalIndex = (int)self.metaArray.count;
        cell.delegate = self;
        cell.userId = self.userId;
        cell.dialogId = self.dialogId;
        
        cell.backgroundColor = ColorWithRGBA(242, 2424, 242, 1.0);
        cell.contentView.backgroundColor = ColorWithRGBA(242, 242, 242, 1.0);
        
        if(self.curCell == nil)
        {
            self.curCell = (MujiDubVCTableViewCell *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
        }
        //[NSIndexPath indexPathWithIndexes:<#(const NSUInteger *)#> length:<#(NSUInteger)#>];
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        if(indexPath.row < self.metaArray.count)
        {
            BOOL bSelected = NO;
            if(indexPath.row == self.mIndex) //判断是否是选中项
            {
                bSelected = YES;
            }
            
            MujiDubRecordModel *myresultmodel;
            MujiDubDialogLinesModel * model = [self.metaArray objectAtIndex:indexPath.row];
            
            for(int j = 0; j < self.myResultArray.count; j ++)
            {
                MujiDubRecordModel *resultmodel = [self.myResultArray objectAtIndex:j];
                if([model.dialogLineID intValue] == [resultmodel.dialoglineid intValue])
                {
                    myresultmodel = resultmodel;
                    break;
                }
            }
            
            //MujiDubDialogLinesModel * model = [self.metaArray objectAtIndex:indexPath.row];
            
            // [cell refreshData:model words:self.wordArray[indexPath.row] selected:bSelected];
            
            [cell refreshData:model words:self.wordArray[indexPath.row] selected:bSelected anyResult:myresultmodel];
        }
            
            return cell;

            
    }else {
        MujiDubPreviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewPreviewCellReusedID forIndexPath:indexPath];
        
        cell.userInteractionEnabled = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.delegete = self;
        
        cell.backgroundColor = ColorWithRGBA(242, 242, 242, 1.0);

        if (self.metaArray.count == 0) {
            
            cell.previewBtn.hidden = YES;
        }else {
            cell.previewBtn.hidden = NO;
        }
        return cell;
    }
}
#pragma mark -  UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(self.metaArray.count > 0 && indexPath.row == self.mIndex)
    {
        if (self.itemHeightArray.count == 0) {
            return 0;
        }
        return [[self.itemHeightArray objectAtIndex:indexPath.row] floatValue];
    }else if (indexPath.row == self.metaArray.count) {
        
        return kScreenHeight - SCREEN_WIDTH/16*9 - 20 - 100;
        
    }
    
    return [[self.itemHeightArray objectAtIndex:indexPath.row] floatValue];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    [self setUpPublishView];
//    return;
//
    return;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //NSLog(@"scrollViewDidScroll  %f", scrollView.contentOffset.y);
  //  NSLog(@"scrollViewDidScroll");
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    
  //  NSLog(@"scrollViewWillBeginDecelerating");

}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.playRecordFinish = NO;
    self.isVideoTapStop = NO;;
    [self refreshPlayRecordStatus:2];

    [self.videoPlayerView pause];
    [self.avAudioPlayer pause];
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

    //NSLog(@"scrollViewDidEndDecelerating");

    CGFloat rowHeight = (kScreenHeight - SCREEN_WIDTH/16*9 - 20)/2.5;
    int row = scrollView.contentOffset.y / rowHeight;
    
    CGFloat total = 0;
    
    for (int i = 0; i< self.itemHeightArray.count; i++) {
        
        NSNumber *height = [self.itemHeightArray objectAtIndex:i];
        total += [height intValue];
       // NSLog(@"%f   %f", scrollView.contentOffset.y, total);
        if (total >= scrollView.contentOffset.y) {
            
            row = i;
           // NSLog(@" ------- %d", row);
            break;
        }
    }
    
    self.mIndex = row;
    [self.tableView reloadData];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    self.playRecordFinish = NO;

    [self playVideo];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    //NSLog(@"scrollViewDidEndDragging    %d", decelerate);

    if(!decelerate)
    {
        CGFloat rowHeight = (kScreenHeight - SCREEN_WIDTH/16*9 - 20)/2.5;
        int row = scrollView.contentOffset.y / rowHeight;
        
        
        CGFloat total = 0;
        for (int i = 0; i< self.itemHeightArray.count; i++) {
            
            NSNumber *height = [self.itemHeightArray objectAtIndex:i];
            total += [height intValue];
            
           // NSLog(@"%f   %f", scrollView.contentOffset.y, total);
            
            if (total >= scrollView.contentOffset.y) {
                
                row = i;
                break;
            }
        }
        
        [self.tableView reloadData];

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        self.mIndex = row;

        [self playVideo];
        self.playRecordFinish = NO;

    }
    
}

#pragma mark -  MujiDubRecorderDelegate

//  开始录音
- (void)recordingBegin
{
    //NSLog(@" recordingBegin ");
    
    self.isRecording = YES;
    self.tableView.scrollEnabled = NO;
    
    if (self.videoPlayerView.player.volume != 0) {
        self.playerVolume = self.videoPlayerView.player.volume;
    }
    [self.videoPlayerView.player setVolume:0];
    
    if(self.mIndex > self.metaArray.count - 1)
    {
        //NSLog(@"出错了，点击的item 多于数组");
        return;
    }
    self.playing = YES;
    if (!self.playButton.hidden) {
        self.playButton.hidden = YES;
    }
    //self.curCell = (MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
    
    [(MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]] resetBtnStatus:NO playRecordStatus:YES];
    
    MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
    
    Float64 cueStart                   = 0.0;
    cueStart    = 0.001 * [model.cueStart intValue];
    CMTime startTime = CMTimeMake(cueStart*10, 10);
    
    [self.videoPlayerView seekToTime:startTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        
        [self.videoPlayerView play];
        [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
        self.isVideoSeeking = NO;
    }];
}

//  结束录音
- (void)recordingEndWithData:(MujiDubRecordModel *)data
{
    //NSLog(@" recordingEnd ");

    BOOL contain = NO;
    for (MujiDubRecordModel *model in self.myResultArray) {
        if ([model.dialogid intValue] == [data.dialogid intValue] && [model.userId intValue] == [data.userId intValue] && [model.dialoglineid intValue] == [data.dialoglineid intValue]) {
            contain = YES;;
            break;
        }
    }
    if (!contain) {
        //NSLog(@"  adasdasda ");
        [self.myResultArray addObject:data];
    }
    
    self.isRecording = NO;
    self.tableView.scrollEnabled = YES;
    
    NSString *wavPath = [self isWAVFileWith];
    if (wavPath.length != 0) {
        NSError *playerError;
        
        MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
        [cell setRecordResultImageViewStatus:YES];
        [cell resetBtnStatus:NO playRecordStatus:NO];
        //播放录音文件
        self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:wavPath] error:&playerError];
        self.avAudioPlayer.volume = 5.0;
        
        //设置代理
        self.avAudioPlayer.delegate = self;
        if (self.avAudioPlayer == nil)
        {
            //NSLog(@"ERror creating player: %@", [playerError description]);
        }else{
            
            self.playRecordFinish = NO;
            
            self.isRecordPlaying = YES;
            if (self.videoPlayerView.player.volume != 0 ) {
                self.playerVolume = self.videoPlayerView.player.volume;
                
            }
            [self.videoPlayerView.player setVolume:0];
            
            self.isVideoSeeking = YES;
            self.playButton.hidden = YES;
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                           {
                               [self playVideoWhenPlayingRecord];
                           });
        }
    }
}

//  视频下载完  可以播放
- (void)playerPlay:(NSNotification *)not
{
    if (!self.preViewStatus) {  // 正常播放
        
        self.tableView.userInteractionEnabled = YES;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.loadingBackView.hidden = YES;
            self.loadingView.hidden = YES;

        });
        
        [self.videoPlayerView play];

    }else {//  预览模式下
    
        //NSLog(@"  预览模式下 -------------- ");
        
        self.playButton.enabled = YES;
        
    }
    
}

#pragma mark -  ////////
//  播放视频
-(void)playVideo
{
    
    self.loadingBackView.hidden = YES;
    self.loadingView.hidden = YES;
    
    if (self.playerVolume != 0) {
        [self.videoPlayerView.player setVolume:self.playerVolume];
    }
    float volume = self.videoPlayerView.player.volume;
    if (volume != 0) {
        self.playerVolume = volume;
    }
    
    if(self.mIndex > self.metaArray.count - 1)
    {
        //NSLog(@"出错了，点击的item 多于数组");
        return;
    }
    self.playing = YES;
    if (!self.playButton.hidden) {
        self.playButton.hidden = YES;
    }
    
    //self.curCell = (MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];

    [(MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]] resetBtnStatus:NO playRecordStatus:YES];
    
    MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
    
    Float64 cueStart                   = 0.0;
    cueStart    = 0.001 * [model.cueStart intValue];
    CMTime startTime = CMTimeMake(cueStart*10, 10);
    
    
//    if (self.mIndex > 0) {
//        startTime = CMTimeMake(cueStart*10, 10);
//    }
    
    [self.videoPlayerView seekToTime:startTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        
        [self.videoPlayerView play];
        [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
        self.isVideoSeeking = NO;
    }];
}

//  播放录音时 同步播放视频
-(void)playVideoWhenPlayingRecord
{
    [self.videoPlayerView.player setVolume:0];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!self.isVideoTapStop) {
            self.playButton.hidden = YES;
        }
    });
    if(self.mIndex > self.metaArray.count - 1)
    {
        //NSLog(@"出错了，点击的item 多于数组");
        return;
    }
    self.playButton.hidden = YES;
    //self.curCell = (MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
    
    [(MujiDubVCTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]] resetBtnStatus:NO playRecordStatus:YES];
    
    MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
    
    Float64 cueStart                   = 0.0;
    cueStart    = 0.001 * [model.cueStart intValue];
    CMTime startTime = CMTimeMake(cueStart*10, 10);
    
    
    //[self beginCountdown];
    
    [self beginCountdown];
    
    [self.videoPlayerView seekToTime:startTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        
        [self.avAudioPlayer play];

        [self.videoPlayerView play];
        
        self.playVideoAndRecord = YES;

        MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
        
        //[cell resetBtnStatus:NO playRecordStatus:NO];
        
        [cell setPlayRecordStatus:1];

        
        
        [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
        self.isVideoSeeking = NO;
    }];
    
    self.playRecordFinish = YES;
}


- (void)videoTimeTick:(CMTime)time
{
    
    self.loadingBackView.hidden = YES;
    self.loadingView.hidden = YES;

    if (self.preViewStatus) {// 预览状态
        
        Float64 seconds = CMTimeGetSeconds(time);
        
        float current=CMTimeGetSeconds(time);
        
        NSInteger static minit;
        NSInteger static second;
        minit = current / 60;
        second = current - 60 * minit;
        
        if (self.metaArray.count == 0) {
            return;
        }
        if (self.mIndex == self.metaArray.count) {
            //[self.videoPlayerView pause];
            
            [self previewFinish];
            return;
        }
        
        MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
        
        Float64 cueEnd                   = 0.0;
        cueEnd   = 0.001 * [model.cueEnd intValue];
        
        Float64 cueStart                   = 0.0;
        cueStart   = 0.001 * [model.cueStart intValue];

        
        float duration = [self.duration floatValue];
        self.timeLabel.text = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%02ld:%02ld", minit, second]];

        if (duration != 0) {
            
            [self.timeProgrssView setProgress:(current/duration)];
        }
        
        Float64 currentDialogLineCueEndSeconds = cueEnd;
        if (seconds >= currentDialogLineCueEndSeconds) {
        
            if (self.avAudioPlayerPause) {
                return;
            }
            self.mIndex ++;
        }else if (seconds >= cueStart && seconds <cueEnd) {
        
            self.subTitleLabel.text = model.transcript;
           // NSLog(@"    %d    %f  ---- %f    %f ", self.mIndex, seconds, cueStart, cueEnd);
            
            if (!self.avAudioPlayerPlaying && !self.avAudioPlayerPause) {
                self.avAudioPlayerPlaying = YES;
                self.avAudioPlayerPause = NO;
                // NSLog(@"  play ");
                self.dubRecordPlayBegin = YES;
            }
            
            if (self.mIndex == 0) {
                
                    [self .avAudioPlayer play];
                    self.avAudioPlayerPlaying = YES;
                    self.avAudioPlayerPause = NO;
                    // NSLog(@"  play ");
                    self.dubRecordPlayBegin = YES;
                    self.previewRecordPlayBegin = YES;
            }
        }
    }else if (self.playVideoAndRecord) { // 同时播放录音跟视频
    
#if 1
        MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
        
        Float64 cueEnd                   = 0.0;
        cueEnd   = 0.001 * [model.cueEnd intValue];
        
        Float64 seconds = CMTimeGetSeconds(time);
        Float64 currentDialogLineCueEndSeconds = cueEnd;
        
        float current=CMTimeGetSeconds(time);
        
        NSInteger static minit;
        NSInteger static second;
        minit = current / 60;
        second = current - 60 * minit;

        NSLog(@"%f    %f ", cueEnd, seconds);
        
        self.timeLabel.text = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%02ld:%02ld", minit, second]];
        float duration = [self.duration floatValue];
        
        if (duration != 0) {
            [self.timeProgrssView setProgress:(current/duration)];
            float duration = [self.duration floatValue];
            if (duration != 0) {
                NSInteger  durationMinute;
                NSInteger  durationSecond;
                durationMinute = duration / 60;
                durationSecond = duration - 60 * durationMinute;
                self.totalTimeLabel.text = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%02ld:%02ld", durationMinute, durationSecond]];
            }
        }
        if (seconds >= currentDialogLineCueEndSeconds) {
            
            NSLog(@"refreshPlayRecordStatus");
            NSLog(@"%f    %f ", cueEnd, seconds);

            NSLog(@" 当前线程  %@",[NSThread currentThread]);

            dispatch_async(dispatch_get_main_queue(), ^{
                
                MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
                
                [cell setPlayRecordStatus:2];
                if (!cell.isRecording) {
                    self.playButton.hidden = NO;

                }
            });
            self.playVideoAndRecord = NO;
            [self.avAudioPlayer pause];
            [self.videoPlayerView pause];
            
            
            self.isVideoTapStop = YES;
            self.playRecordFinish = YES;
            
            self.isRecordPlaying = NO;

            
            if (!self.playing) {
                self.playRecordFinish = YES;
                //self.playButton.hidden = NO;
                self.isVideoTapStop = YES;
            }
        }
#endif
        
    }else {//   录音状态
        
        //self.videoTimeTickStop = NO;
        
        Float64 seconds = CMTimeGetSeconds(time);
        
        float current=CMTimeGetSeconds(time);
        
        NSInteger static minit;
        NSInteger static second;
        minit = current / 60;
        second = current - 60 * minit;
        
        if (self.metaArray.count == 0) {
            return;
        }
        MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
        
        Float64 cueEnd                   = 0.0;
        cueEnd   = 0.001 * [model.cueEnd intValue];
        
        // cueEnd = 14.320;
        
        Float64 currentDialogLineCueEndSeconds = cueEnd;
        if (seconds >= currentDialogLineCueEndSeconds)
        {
            //self.videoTimeTickStop = YES;
            [self.videoPlayerView pause];
            self.playing = NO;

            if (!self.isGuideAdded) {
                [self addGuideView];
            }
            _stop = YES;
            _playing = NO;
            //_recordBtn.enabled = YES;
            // self.playButton.hidden = NO;
            
            BOOL bFInd = NO;
            for(int j = 0; j < self.myResultArray.count; j ++)
            {
                MujiDubRecordModel *resultmodel = [self.myResultArray objectAtIndex:j];
                if([model.dialogLineID intValue] == [resultmodel.dialoglineid intValue])
                {
                    bFInd = YES;
                    break;
                }
            }
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
               // NSLog(@"isVideoTapStop  %d  playRecordFinish  %d", self.isVideoTapStop, self.playRecordFinish)
                
                if (!self.isVideoTapStop) {
                    
                    if (!self.playRecordFinish) {
                        
                       // NSLog(@"---------------------");
                        
                        if (!self.isRecording) {
                            [self playVideo];
                            self.isVideoSeeking = YES;

                        }else {
                        }
                        
                    }else {//  播放录音结束后 不重复播放
                    }
                }
            });
            return;
        }else {
            
            _playing = YES;
            
            self.timeLabel.text = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%02ld:%02ld", minit, second]];
            float duration = [self.duration floatValue];
            
            if (duration != 0) {
                
                [self.timeProgrssView setProgress:(current/duration)];
                
                float duration = [self.duration floatValue];
                
                if (duration != 0) {
                    NSInteger  durationMinute;
                    NSInteger  durationSecond;
                    durationMinute = duration / 60;
                    durationSecond = duration - 60 * durationMinute;
                    self.totalTimeLabel.text = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%02ld:%02ld", durationMinute, durationSecond]];
                }
            }
            
            if (seconds == self.previousVideoTimeSeconds)
            {
                /* RETURN when time hasn't changed from previous video time tick - nothing else to do */
                return;
            }
            // remember the current time for the next tick
            [self setPreviousVideoTimeSeconds:seconds];
        }

    }
}
- (BOOL)isHaveResult
{
    MujiDubDialogLinesModel * model = [self.metaArray objectAtIndex:self.mIndex];

    for (MujiDubRecordModel *resultmodel in self.myResultArray) {
        if ([model.dialogLineID integerValue] == [resultmodel.dialoglineid integerValue]) {
            return YES;
            break;
        }else {
            return NO;
        }
    }
    return NO;
}


//- (void)timer
//{
//    MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
//    
//    CMTimeValue curValue = self.videoPlayerView.player.currentItem.duration.value;
//    Float64 cur = CMTimeGetSeconds(self.videoPlayerView.player.currentItem.duration);
//    if(cur >= [model.cueEnd intValue]){
//        [self.avTimer invalidate];
//        [self.videoPlayerView pause];
//    }
//}
#pragma mark - 预览状态下播放录音
- (void)playDubRecord
{
    //_dubRecordPlayBegin = YES;
    self.mIndex = 0;
    
    NSString *userId = self.userId;

    MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
    NSString *userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
    userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/integrateData", userId, self.dialogId]];
    
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4",
                          userId,
                          self.dialogId];
    NSString *wavFilePath = [userAudioDirectory stringByAppendingPathComponent:fileName];
    
    NSError *playerError;
    //播放录音文件
    self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:wavFilePath] error:&playerError];
    self.avAudioPlayer.volume = 5.0;
    
    //设置代理
    self.avAudioPlayer.delegate = self;
    if (self.avAudioPlayer == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        //[self.avAudioPlayer play];
    }
    self.previewRecordPlayBegin = NO;

}

- (void)testBtnAction
{
    
    NSString *userId = self.userId;
    
    MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
    NSString *userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
    userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/integrateData", userId, self.dialogId]];
    
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4",
                          userId,
                          self.dialogId];
    NSString *wavFilePath = [userAudioDirectory stringByAppendingPathComponent:fileName];
    
    NSError *playerError;
    //播放录音文件
    self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:wavFilePath] error:&playerError];
    self.avAudioPlayer.volume = 5.0;
    
    //设置代理
    self.avAudioPlayer.delegate = self;
    if (self.avAudioPlayer == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        [self.avAudioPlayer play];
    }
    
    return;

#if 0
    
    NSString *userId = self.userId;
    
    MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
    NSString *userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
    userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/sectionData", userId, self.dialogId]];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *files = [manager subpathsAtPath:userAudioDirectory];
    
    NSLog(@"%@", files);
    
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray = [files sortedArrayUsingComparator:sort];
    NSLog(@"字符串数组排序结果%@",resultArray);
    
    if (resultArray.count != self.metaArray.count) {
        return;
    }
    NSMutableArray *sourceURLs = [NSMutableArray arrayWithCapacity:10];
    for (NSString *fileName in resultArray) {
        NSString *filePath = [userAudioDirectory stringByAppendingPathComponent:fileName];
        [sourceURLs addObject:[NSURL fileURLWithPath:filePath]];
    }
    
    userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
    userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/integrateData", userId, self.dialogId]];
    
    NSError *outError = nil;
    
    if ([manager fileExistsAtPath:userAudioDirectory])
    {
        //return YES;
        //[_mutablePaths setObject:userAudio forKey:@(MujiDubFilePathDirectoryUserAudio)];
    }
    else
    {
        if ([manager createDirectoryAtPath:userAudioDirectory withIntermediateDirectories:YES attributes:nil error:&outError])
        {
        }else {
            return;
        }
    }
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4",
                          userId,
                          self.dialogId];
    NSString *path = [userAudioDirectory stringByAppendingPathComponent:fileName];
    
    [MujiAudioComposition sourceURLs:sourceURLs dialogs:self.metaArray composeToURL:[NSURL fileURLWithPath:path] completed:^(NSError *error) {
        
    }];
    
#endif
}
- (void)previewFinish
{
    
    [self.videoPlayerView pause];
    self.playButton.hidden = NO;
    self.isVideoTapStop = YES;

    self.mIndex = 0;
    self.avAudioPlayerPause = YES;
    
    MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
    
    Float64 cueStart                   = 0.0;
    cueStart    = 0.001 * [model.cueStart intValue];
    CMTime startTime = CMTimeMake(cueStart*10, 10);
    
    
    //    if (self.mIndex > 0) {
    //        startTime = CMTimeMake(cueStart*10, 10);
    //    }
    
    [self.videoPlayerView seekToTime:startTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        
        self.subTitleLabel.text = model.transcript;

        [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
        self.isVideoSeeking = NO;
    }];
    
    
}
#pragma mark - 播放录音
//播放录音
- (void)playRecordBtnDidClickedWithScore:(NSString *)score status:(int)status
{
    
    if (status == 1) {//  从开始到结束
        //NSString *wavPath = [self.videoSpeechWAVPath objectForKey:indexStr];
        self.lineScore = score;
        
        NSString *wavPath = [self isWAVFileWith];
        if (wavPath.length != 0) {
            NSError *playerError;
            
            MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
            
            [cell setRecordResultImageViewStatus:YES];
            
            //[cell resetBtnStatus:NO playRecordStatus:NO];
            
            [cell setPlayRecordStatus:1];
            
            //播放录音文件
            self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:wavPath] error:&playerError];
            self.avAudioPlayer.volume = 5.0;
            
            //设置代理
            self.avAudioPlayer.delegate = self;
            if (self.avAudioPlayer == nil)
            {
                NSLog(@"ERror creating player: %@", [playerError description]);
            }else{
                
                self.playRecordFinish = NO;
                
                self.isRecordPlaying = YES;
                if (self.videoPlayerView.player.volume != 0 ) {
                    self.playerVolume = self.videoPlayerView.player.volume;
                }
                [self.videoPlayerView.player setVolume:0];
                
                self.isVideoSeeking = YES;
                self.playButton.hidden = YES;
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                               {
                                   [self playVideoWhenPlayingRecord];
                               });
            }
        }
        [self refreshPlayRecordStatus:1];

    }else if (status == 2){ //从暂停到开始
        
        [self.videoPlayerView play];
        [self.avAudioPlayer play];
        
        
        [self refreshPlayRecordStatus:1];

        
//        MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
//        
//        [cell setRecordResultImageViewStatus:YES];
//        
//        [cell resetBtnStatus:NO playRecordStatus:NO];
//        
//        [cell setPlayRecordStatus:1];
    }
}

// 暂停播放录音跟视频
- (void)pausePlayRecord
{
    
    self.playingRecordPauseBegintime = [[MujiDubTools share] getCurrentTime];
    
    [self.avAudioPlayer pause];
    [self.videoPlayerView pause];
    
    
    [self refreshPlayRecordStatus:0];
    
}

- (void)refreshPlayRecordStatus:(int)status
{
    
    NSLog(@" ---1111111-- ");
    
    MujiDubVCTableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.mIndex inSection:0]];
    
    [cell setPlayRecordStatus:status];

    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.mIndex inSection:0];
    //[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];

    
    
}
// 开始计时
- (void)beginCountdown
{
    self.timerBegintime = [[MujiDubTools share] getCurrentTime];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __block float time = 0; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 0.01*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            
            time += 0.01;
            
            float times = [[MujiDubTools share] dateTimeDifferenceWithStartTime:self.timerBegintime];
            float pauseTime = [[MujiDubTools share] dateTimeDifferenceWithStartTime:self.playingRecordPauseBegintime endTime:[[MujiDubTools share] getCurrentTime]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSString *title = [NSString stringWithFormat:@"%.2fs", time];
            });
            MujiDubDialogLinesModel *model =  [self.metaArray objectAtIndex:self.mIndex];
            
            float dialogDuration = [self getDialogDurationWithModel:model];
            
#if 1
            if (times - pauseTime > dialogDuration) {
                   // NSLog(@" dialogDuration %f   time %f   times %f", dialogDuration, time, times);
                    
                [self.avAudioPlayer pause];
                [self.videoPlayerView pause];
                
                if (_timer) {
                    dispatch_source_cancel(_timer);
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                   // self.playButton.hidden = NO;
                    self.isVideoTapStop = YES;
                    self.playRecordFinish = YES;
                    
                    self.isRecordPlaying = NO;
                });
                
                if (!self.playing) {
                    self.playRecordFinish = YES;
                    //self.playButton.hidden = NO;
                    self.isVideoTapStop = YES;
                }
            }
#endif
        });
        dispatch_resume(_timer);
    });
}
//获取当前时间
- (NSString *)getCurrentTime
{
    
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYY-MM-dd  HH:mm:ss:SSS"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];

   // NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:timeDate];
    return locationString;
}
//  获取一句话的总时间
- (float)getDialogDurationWithModel:(MujiDubDialogLinesModel *)curmodel
{
    
    // NSLog(@"%@  %@", curmodel.cueEnd, curmodel.cueStart);
    
    int start = [curmodel.cueStart intValue];
    int end = [curmodel.cueEnd intValue];
    
    int duration = end - start;
    
    NSInteger  minit;
    NSInteger  second;
    minit = duration / 60;
    second = duration - 60 * minit;
    
    //NSString *
    
    return ((float)duration/1000);
    
}
// 判断录音文件是否存在
- (NSString *)isWAVFileWith
{
    MujiDubDialogLinesModel * model = [self.metaArray objectAtIndex:self.mIndex];

    NSString *userId = self.userId;
    
    //model.dialogId = self.dialogId;
    //model.dialogLineID = @"654321";

    NSString *libaryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *wavPath = [libaryPath stringByAppendingPathComponent:@"UserAudio"];
    wavPath = [wavPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/sectionData", userId, model.dialogId]];

    NSString *secondPath = [wavPath stringByAppendingPathComponent:@"UserWAVCopy"];
    NSString *wavName = [NSString stringWithFormat:@"%@_%@_%@.wav",
                         userId,
                         model.dialogId,
                         model.dialogLineID];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    NSString *wavName = [NSString stringWithFormat:@"%@_%@_%@.wav", userID, self.curModel.dialogId, self.curModel.dialogLineID];
    NSString *filePath = [wavPath stringByAppendingPathComponent:wavName];
    
    if(![fileManager fileExistsAtPath:filePath]) {//如果不存在
        return @"";
    }else {
        return filePath;
    }
}


#pragma mark -- LetterViewDelegate
-(void)goonPlay
{
     //_letterView.hidden = YES;
   //  [_selectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.videoPlayerView play];
}
// 从数据库获取 录音完成的句子
-(void)getResultFromDB
{

    NSString *userId = self.userId;

    [self.myResultArray removeAllObjects];
    
    NSArray *array = [[MujiDubDatabaseManager shareManager] queryAllHistoryModelWithUserId:userId dialogid:self.dialogId];
    
    if (array.count != 0) {
        
        for (MujiDubRecordModel *model in array) {
            [self.myResultArray addObject:model];
        }
    }
}

#pragma mark -  MujiDubPreviewTableViewCellDElegate
//  预览配音按钮事件
- (void)previewBtnAction
{
    if (self.isRecording) {
        return;
    }
    
    [self.videoPlayerView pause];
    self.playButton.hidden = NO;
    self.isVideoTapStop = YES;

    [self.avAudioPlayer pause];
    if (_timer) {
        dispatch_cancel(_timer);
    }
    
#if 0
    Float64 cueStart                   = 0.05;
    CMTime startTime = CMTimeMake(cueStart, 1.0);
    
    [self.videoPlayerView.player setVolume:0];

    [self.videoPlayerView seekToTime:startTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        
        //[self.videoPlayerView play];
        [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
        self.isVideoSeeking = NO;
        self.playButton.enabled = YES;

    }];
    
    self.mIndex = 0;
    [self mergeRecordData];
    [self setupSaveViewAnimation];
    return;
#endif
    
    NSString *userId = self.userId;

    NSArray *array = [[MujiDubDatabaseManager shareManager] queryAllHistoryModelWithUserId:userId dialogid:self.dialogId];
    if (array.count == self.metaArray.count && self.metaArray.count != 0) {
        
        Float64 cueStart                   = 0.05;
        CMTime startTime = CMTimeMake(cueStart*10, 10);
        
        [self.videoPlayerView.player setVolume:0];
        
        [self.videoPlayerView seekToTime:startTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
            
            //[self.videoPlayerView play];
            [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
            self.isVideoSeeking = NO;
            self.playButton.enabled = YES;
            
        }];
        
        self.mIndex = 0;
        [self mergeRecordData];
        [self setupSaveViewAnimation];
        
    }else {
        [[MujiHUDManager shareManager] showHUDWithTitle:@"配音未完成，无法预览!" mode:MBProgressHUDModeText delay:1.0];
    }
}
// 配音成功弹框
- (void)setUpPublishView
{
    UIView *publishView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight - CGRectGetMaxY(self.videoPlayerView.frame))];
    publishView.tag = 123456;
    publishView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:publishView];

    
    [UIView animateWithDuration:0.25 animations:^{
        [publishView setFrame:CGRectMake(0, CGRectGetMaxY(self.videoPlayerView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.videoPlayerView.frame))];
    }];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 175)/2, 63, 175, 128)];
    imageView.image = [UIImage imageNamed:@"icon_dub_success"];
    
    //imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon_dub_success" ofType:@"png"]]];
    [publishView addSubview:imageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, CGRectGetMaxY(imageView.frame)+20, kScreenWidth - 100 - 100, 21)];
    label.text = @"配音成功";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = ColorWithRGBA(74, 74, 74, 1.0);
    label.font = [UIFont systemFontOfSize:16];
    [publishView addSubview:label];
    
    UIButton *publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    publishBtn.frame = CGRectMake((kScreenWidth - 240)/2, CGRectGetMaxY(label.frame) + 84, 240, 44);
    publishBtn.backgroundColor = ColorWithRGBA(255, 195, 0, 1.0);
    publishBtn.layer.cornerRadius = 44/2;
    publishBtn.layer.masksToBounds = YES;
    [publishBtn setTitle:@"发布并分享" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [publishBtn addTarget:self action:@selector(publishBtnDidclicked:) forControlEvents:UIControlEventTouchUpInside];
    [publishView addSubview:publishBtn];
    
}

- (void)setupSaveViewAnimation
{
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    [self.view.window addSubview:backView];
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];
    containerView.center = CGPointMake(backView.frame.size.width/2, backView.frame.size.height/2);
    containerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.26];
    containerView.layer.cornerRadius = 20;
    containerView.layer.masksToBounds = YES;
    [backView addSubview:containerView];
    
    
    UIProgressView *progrssView = [[UIProgressView alloc] initWithFrame:CGRectMake(11, (140 - 2)/2, 140 - 11 - 11, 2)];
    progrssView.trackTintColor = [ColorWithRGBA(255, 255, 255, 1.0) colorWithAlphaComponent:0.5];
    progrssView.progressTintColor = ColorWithRGBA(255, 255, 255, 1.0);
    //[self.timeProgrssView setProgress:0.3];
    progrssView.trackTintColor = ColorWithRGBA(255, 255, 255, 0.2);
    [containerView addSubview:progrssView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(progrssView.frame) + 10, 140, 21)];
    label.text = @"保存中";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = ColorWithRGBA(255, 255, 255, 1.0);
    label.font = [UIFont systemFontOfSize:13];
    [containerView addSubview:label];

    __block float time = 0; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 0.01*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        
        time += 0.01;
        
                dispatch_async(dispatch_get_main_queue(), ^{
            //设置界面的按钮显示 根据自己需求设置
            [progrssView setProgress:time];
            
            NSString *title = [NSString stringWithFormat:@"%.2fs", time];
        });
        
        if (time >= 1.5) {
            
            if (_timer) {
                dispatch_source_cancel(_timer);
            }
            self.preViewStatus = YES;

            dispatch_async(dispatch_get_main_queue(), ^{
 
                [backView removeFromSuperview];
                
                [self setUpPublishView];
                //return;
                
                
                self.subTitleLabel.hidden = NO;
                
                [self.timeProgrssView setProgress:0];
                
                [self playDubRecord];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                
                self.isVideoTapStop = NO;;
                self.playRecordFinish = NO;
                
                self.playButton.hidden = YES;

                self.timeView.hidden = YES;
                [self.videoPlayerView play];
                if (self.avAudioPlayerPause) {
                    
                    if (!self.previewRecordPlayBegin) {
                        return;
                    }
                    [self.avAudioPlayer play];
                    self.avAudioPlayerPause = NO;
                }
                
            });
            
        }
    });
    dispatch_resume(_timer);
}

//  合成录音成 一整段MP4
- (void)mergeRecordData
{
    NSString *userId = self.userId;
    
    MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
    NSString *userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
    userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/sectionData", userId, self.dialogId]];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *files = [manager subpathsAtPath:userAudioDirectory];
    
    NSLog(@"%@", files);
    
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|
    NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    NSArray *resultArray = [files sortedArrayUsingComparator:sort];
    NSLog(@"字符串数组排序结果%@",resultArray);
    
    if (resultArray.count != self.metaArray.count) {
        return;
    }
    NSMutableArray *sourceURLs = [NSMutableArray arrayWithCapacity:10];
    for (NSString *fileName in resultArray) {
        NSString *filePath = [userAudioDirectory stringByAppendingPathComponent:fileName];
        [sourceURLs addObject:[NSURL fileURLWithPath:filePath]];
    }
    
    userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
    userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/integrateData", userId, self.dialogId]];
    
    NSError *outError = nil;
    
    if ([manager fileExistsAtPath:userAudioDirectory])
    {
        //return YES;
        //[_mutablePaths setObject:userAudio forKey:@(MujiDubFilePathDirectoryUserAudio)];
    }
    else
    {
        if ([manager createDirectoryAtPath:userAudioDirectory withIntermediateDirectories:YES attributes:nil error:&outError])
        {
        }else {
            return;
        }
    }
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4",
                          userId,
                          self.dialogId];
    NSString *path = [userAudioDirectory stringByAppendingPathComponent:fileName];
    
    [MujiAudioComposition sourceURLs:sourceURLs dialogs:self.metaArray composeToURL:[NSURL fileURLWithPath:path] completed:^(NSError *error) {
        
    }];
    
    
}

//  发布按钮事件
- (void)publishBtnDidclicked:(UIButton *)btn
{
    int reachabilityStatus = [[[NSUserDefaults standardUserDefaults] objectForKey:kReachabilityStatus] intValue];
    if (reachabilityStatus == 0) {
        [[MujiHUDManager shareManager] showHUDWithTitle:@"离线状态无法发布，请检查网络！" mode:MBProgressHUDModeText delay:1.0];

    }else {
        
    }

//    UIView *view = [self.view viewWithTag:123456];
//    
//    [UIView animateWithDuration:0.25 animations:^{
//        [view setFrame:CGRectMake(0, kScreenHeight + CGRectGetMaxY(self.videoPlayerView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.videoPlayerView.frame))];
//    }];

    
    
}

//  视频view 手势事件
- (void)videoPlayViewTap
{
    if (self.isRecordPlaying) {//播放录音的时候  禁止暂停视频
        return;
    }

    self.playRecordFinish = NO;

    if(self.isRecording)
    {
        return;
    }
    if (self.videoPlayerView.player)
    {
        if (self.videoPlayerView.player.rate > 0.0)
        {
            // Video is playing, so pause it (Play button will show as soon as video is paused):
            if (self.isVideoSeeking) {
                return;
            }
            
            [self.videoPlayerView pause];
            self.playButton.hidden = NO;
            self.isVideoTapStop = YES;
            
            if (self.preViewStatus) {
                self.timeView.hidden = NO;
                [self.avAudioPlayer pause];
                self.avAudioPlayerPause = YES;
            }
        }
        else
        {
        }
    }
    
}
//  播放按钮事件
-(void)playAction
{
    self.isVideoTapStop = NO;;
    self.playRecordFinish = NO;

    self.playButton.hidden = YES;
    [self.videoPlayerView play];
    
    if (self.preViewStatus) {
        self.timeView.hidden = YES;
        
        if (self.avAudioPlayerPause) {
            
            if (!self.previewRecordPlayBegin) {
                return;
            }
            [self.avAudioPlayer play];
            self.avAudioPlayerPause = NO;
        }
    }else {
        [self.videoPlayerView.player setVolume:self.playerVolume];
    }
}

// 字典弹框
-(void)showLetterInfoView:(int)index
{
    [self.videoPlayerView pause];
    
    int reachabilityStatus = [[[NSUserDefaults standardUserDefaults] objectForKey:kReachabilityStatus] intValue];
    if (reachabilityStatus == 0) {
        [[MujiHUDManager shareManager] showHUDWithTitle:@"离线状态下无法查看单词注解" mode:MBProgressHUDModeText delay:1.0];

    }else {
        
        self.playButton.hidden = NO;
        
        [self.videoPlayerView pause];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.videoPlayerView pause];
            if (self.avAudioPlayer) {
                [self.avAudioPlayer pause];
            }
        });
        
        //[[HUDManager shareManager] showHUDWithTitle:@"" mode:MBProgressHUDModeIndeterminate];
        if (!_letterView) {
            _letterView = [[MujiDubDictionaryView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight)];
            //        _letterView.delegate = self;
            //        _letterView.hidden = YES;
            //        _letterView.parentVC = self;
            
            [self.view addSubview:_letterView];
        }
        
        __weak __typeof(self) weakSelf = self;
        
        _letterView.dictViewAction = ^(int action){
            
            weakSelf.letterView.hidden = YES;
            //[weakSelf.videoPlayerView play];
            //weakSelf.playButton.hidden = YES;
            
            [(MujiDubVCTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.mIndex inSection:0]] setWordBackGroundColorWithIndex:index status:0];
            
        };
        
        if(index >= [_wordArray[self.mIndex] count])
        {
            return;
        }
        MujiDubWordModel *wordModel = _wordArray[self.mIndex][index];
        
        [_letterView refreshDataWithUrl:wordModel.orthography];
        
        
        [_letterView setFrame:CGRectMake(0, kScreenHeight + 200, kScreenHeight, kScreenHeight)];
        [UIView animateWithDuration:0.5 animations:^{
            _letterView.hidden = NO;
            [_letterView setFrame:CGRectMake(0, 0, kScreenHeight, kScreenHeight)];
            
        } completion:^(BOOL finished) {
            
        }];
        //_letterView.hidden = NO;
    }
}
- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    if ([self.slowSpeakAudioPlayer isPlaying]) {
        [self.slowSpeakAudioPlayer stop];
    }
}
- (void)dealloc
{
    //[self.db close];
    NSLog(@"  MujiDubViewController     dealloc");
}
- (void)backAction
{
    //[super ];
    if (self.avAudioPlayer != nil) {
        [self.avAudioPlayer stop];
        self.avAudioPlayer = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
    
    [self setupDealloc];
}

- (void)hideRecordAllHUDsAnimated:(BOOL)animated
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:animated];
    self.hud = nil;
}
- (void)hideRecordAllHUDsAnimated:(BOOL)animated withDelay:(int)delay
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:animated];
        
        self.hud = nil;
    });
}

- (void)showAlertView:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

@end
